package itsm.isperp.framework.security.license;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.security.encoding.CertificateCoder;
import sun.tools.tree.ThisExpression;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.commons.codec.binary.Hex;
import org.springframework.security.core.session.SessionRegistry;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-2-28
 * @since 1.0
 * 
 */
public final class LicenseUtils {

	public static final String[] initLicense() throws IOException {
	    
		String path1=LicenseUtils.class.getClassLoader().getResource("").getPath();
		/*String file = ContextHolder.getApplicationClassPath()
				+ "isperp.license";*/
		path1=path1.replaceAll("%20", " ");
		String filePath=path1+ "isperp.license";
		System.out.print("license目录："+filePath);
		filePath=filePath.substring(1);

		File f = new File(filePath);
		if (!f.exists()) {
			return null;
		}

		String[] result = new String[2];

		FileInputStream fis = new FileInputStream(filePath);
		InputStreamReader reader = new InputStreamReader(fis, "UTF-8");

		BufferedReader br = new BufferedReader(reader);
		String s1 = null;
		int i = 0;
		while ((s1 = br.readLine()) != null) {
			result[i] = s1;
			i++;
		}
		br.close();
		reader.close();

		return result;
	}

	public static final String getData() throws Exception {
		String certificatePath =LicenseUtils.class.getClassLoader().getResource("").getPath()
				+ "key.cer";
		byte[] encodedData = Hex
				.decodeHex(ContextHolder.LIC_DATA.toCharArray());
		byte[] decodedData = CertificateCoder.decryptByPublicKey(encodedData,
				certificatePath);
		return new String(decodedData);

	}

	public static final boolean validata() {
		Date now = new Date();
		if (ContextHolder.SERVER_INFO == null)
			return false;

		SessionRegistry sessionRegistry = ContextHolder
				.getSpringBean("sessionRegistry");

		int ucount = sessionRegistry.getAllPrincipals().size();

		return now.compareTo(ContextHolder.SERVER_INFO.getTodate()) != 1
				&& ContextHolder.SERVER_INFO.getMaxuser() > ucount;
	}

	public static final boolean verify() throws Exception {
		String certificatePath =LicenseUtils.class.getClassLoader().getResource("").getPath()
				+ "key.cer";
		byte[] encodedData = Hex
				.decodeHex(ContextHolder.LIC_DATA.toCharArray());
		return CertificateCoder.verify(encodedData, ContextHolder.LIC_SING,
				certificatePath);

	}
}
